/**
 * @file utils/helper.js
 *  常用工具方法
 * @author maoquan(maoquan@htsc.com)
 */
import lodash from 'lodash';
const helper = {
	/**
	 * 将{ a: 1, b: 2 } => a=1&b=2
	 * @param {object} query
	 */
	queryToString(query = {}) {
		const encode = encodeURIComponent;
		return Object.keys(query).map(
			key => (`${encode(key)}=${encode(query[key])}`),
		).join('&');
	},

	/**
	 * 由?a=1&b=2 ==> {a:1, b:2}
	 * @param {string} search 一般取自location.search
	 */
	getQuery(search) {
		const query = {};
		// 去掉`?`
		const searchString = search.slice(1);
		if (searchString) {
			searchString.split('&').map(
				item => item.split('='),
			).forEach(
				item => (query[item[0]] = item[1]),
			);
		}
		return query;
	},

	isLocalStorageSupport() {
		const KEY = 'STORAGE_TEST_KEY';
		try {
			localStorage.setItem(KEY, KEY);
			localStorage.removeItem(KEY);
			return true;
		} catch (e) {
			return false;
		}
	},

	/**
	 * 获取属性的属性值
	 * 针对类似 `a.b.c` 的命名路径，获取最后的 `c` 的属性
	 *
	 * @param {object} object 要获取值的对象
	 * @param {string} name 属性名
	 * @return {*}
	 */
	getProperty(object, name) {
		const paths = name.split('.');
		let property = object[paths.shift()];

		while (paths.length) {
			if (property === null || property === undefined) {
				return property;
			}
			property = property[paths.shift()];
		}

		return property;
	},

/**
 * 格式化时间
 * @param {string} dateParms
 */
	dateConvert(dateParms) {
	// 对传入的时间参数进行判断
		if (dateParms instanceof Date) {
			var datetime = dateParms;
		}
	// 判断是否为字符串
		if ((typeof dateParms === 'string') && dateParms.constructor === String) {
	// 将字符串日期转换为日期格式
			var datetime = new Date(Date.parse(dateParms.replace(/-/g, '/')));
		}
	// 获取年月日时分秒
		const year = datetime.getFullYear();
		let month = datetime.getMonth() + 1;
		let date = datetime.getDate();
	// 月，日，时，分，秒 小于10时，补0
		if (month < 10) {
			month = `0${month}`;
		}
		if (date < 10) {
			date = `0${date}`;
		}
	// 拼接日期格式【例如：yyyymmdd】
		const time = year + month + date;
	// 返回处理结果
		return time;
	},

	hasClass(elem, className) {
		return elem.className.indexOf(className) > -1;
	},

	queryArray(array, key, keyAlias = 'key') {
		if (!(array instanceof Array)) {
			return null;
		}
		const item = array.filter(_ => _[keyAlias] === key);
		if (item.length) {
			return item[0];
		}
		return null;
	},

	arrayToTree(array, id = 'id', pid = 'pid', children = 'children') {
		const data = lodash.cloneDeep(array);
		const result = [];
		const hash = {};
		data.forEach((item, index) => {
			hash[data[index][id]] = data[index];
		});

		data.forEach((item) => {
			const hashVP = hash[item[pid]];
			if (hashVP) {
				!hashVP[children] && (hashVP[children] = []);
				hashVP[children].push(item);
			} else {
				result.push(item);
			}
		});
		return result;
	},

	/**
	 * 数组去重
	 */
	 Arrayremoval(obj,arr){
 		let tmpStatus=false;
 		for(let j=0;j<arr.length;j++){
 			if(obj.productId==arr[j].productId){
 				return j;
 				break;
 			}else{
 				tmpStatus=false;
 			}
 		}
 		if(!tmpStatus){
 			return -1;
 		}
 	},
 	Arrayremoval_1(obj,arr){
 		let tmpStatus=false;
 		for(let j=0;j<arr.length;j++){
 			if(obj.key==arr[j].key){
 				return j;
 				break;
 			}else{
 				tmpStatus=false;
 			}
 		}
 		if(!tmpStatus){
 			return -1;
 		}
 	},
	/*
* 参数 data 是导出的数据
* 参数 title 是导出的标题
* showLabel 表示是否显示表头 默认显示
*/

JSONToCSVConvertor(JSONData, ShowLabel){
			//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
			 var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
			 var CSV = '';
			 //Set Report title in first row or line
			 // CSV += ReportTitle + '\r\n\n';
			//This condition will generate the Label/Header
			if (ShowLabel) {
				console.log("ShowLabel?>>>>",arrData,ShowLabel);
					var row = "";
				 //This loop will extract the label from 1st index of on array
					for (var index in ShowLabel) {
						console.log("ShowLabel?12>>>>",index,ShowLabel);
						//Now convert each value to string and comma-seprated
						row += ShowLabel[index] + ',';
				 }
				 row = row.slice(0, -1);
				 console.log("ShowLabel?www>>>>",row);
				 //append Label row with line break
				 CSV += row + '\r\n';
		 }
		 //1st loop is to extract each row
		 for (var i = 0; i < arrData.length; i++) {
				var row = "";
				 //2nd loop will extract each column and convert it in string comma-seprated
					// for (var index in arrData[i]) {
						for(let k in ShowLabel ){
							if(arrData[i][k] == undefined){
								arrData[i][k] = '';
							}

							// row += `${str}${arrData[i][k]},`;
							row += '"' +"\t"+ arrData[i][k] + '",';
								console.log("ShowLabel?>>11",arrData[i][k],'-----------',row);
						}

			 // }
				row.slice(0, row.length - 1);
				console.log("ShowLabel?>>>>",row);
				//add a line break after each row
				CSV += row + '\r\n';
console.log("ShowLabel?>>CSV",CSV);
			}
		 if (CSV == '') {
				 alert("Invalid data");
				return;
		 }
		 //Generate a file name
		var fileName = Date.now();
		var uri = 'data:text/csv;charset=utf-8,\uFEFF' + encodeURIComponent(CSV);
		console.log("ShowLabel?>>>>uri",uri);
		var link = document.createElement("a");
		link.href = uri;

		//set the visibility hidden so it will not effect on your web-layout
		 link.style = "visibility:hidden";
		link.download = fileName + ".csv";

		//this part will append the anchor tag and remove it after automatic click
		 document.body.appendChild(link);
		 link.click();
		document.body.removeChild(link);
	},


};

export default helper;
